package de.metalcon.gwt.client.mainDesign;

import java.util.ArrayList;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.FlowPanel;

import de.metalcon.gwt.client.Metalcon;
import de.metalcon.gwt.client.interactions.AInteraction;
import de.metalcon.gwt.client.pages.APage;

public class MainContent extends FlowPanel {
	static MainContent instance;
	APage page;
	ArrayList<AInteraction> interactions = new ArrayList<AInteraction>();
	private FlowPanel pageContainer = new FlowPanel();

	public MainContent() {
		MenuBar menuBar = new MenuBar();
		add(menuBar);

		add(pageContainer);
		pageContainer.addStyleName(Metalcon.getBundle().css().pageContainer());
		instance = this;
	}

	public void setPage(APage p) {
		if (this.page != null) {
			pageContainer.remove(this.page);
		}
		this.page = p;
		pageContainer.add(p);
	}

	public void addInteraction(AInteraction interaction) {
		interactions.add(interaction);
		interaction.center();
	}

	public void removeInteraction(AInteraction interaction) {
		interactions.remove(interaction);
		interaction.clear();
	}

	public static void OpenPage(APage p) {
		History.newItem(p.getHistoryToken(), false);
		instance.setPage(p);
	}

	public static void CloseInteraction(final AInteraction interaction) {
		String token = History.getToken();
		token = token.replace("$" + interaction.getHistoryActionToken(), "");
		History.newItem(token, false);
		instance.removeInteraction(interaction);
	}

	public static void StartInteraction(final AInteraction interaction) {
		History.newItem(History.getToken() + "$" + interaction.getHistoryActionToken(), false);
		instance.addInteraction(interaction);
	}

	public static void StartInteractions(ArrayList<AInteraction> interactions) {
		for (AInteraction i : interactions) {
			StartInteraction(i);
		}
	}
}